package com.quectel.cms.controller.room;


import com.fasterxml.jackson.core.type.TypeReference;
import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.vo.room.RoomSuspicionOrderHandleReq;
import com.quectel.constant.core.room.GroupRentingRoomConstants;
import com.quectel.constant.core.room.VillageRoomSuspicionOrderConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.room.dto.VillageRoomSuspicionOrderDto;
import com.quectel.core.module.room.service.VillageRoomSuspicionOrderService;
import com.quectel.core.module.village.dto.VillageRoomDto;
import com.quectel.core.module.village.service.VillageRoomService;
import com.quectel.util.aspect.log.annotation.Log;
import com.quectel.util.common.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.RoundingMode;
import java.util.*;

/**
 *
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2023/11/10 11:43
 */
@RestController
@RequestMapping("villageRoomSuspicionOrder")
@Tag(name = "VillageRoomSuspicionOrderController", description = "群租房嫌疑单相关api 请开发者检查描述")
public class VillageRoomSuspicionOrderController extends BaseController {

    @DubboReference
    private VillageRoomSuspicionOrderService villageRoomSuspicionOrderService;
    @DubboReference
    private VillageRoomService villageRoomService;

    @PostMapping("handle")
    @RequirePermissions(values = "villageRoomSuspicionOrder:handle")
    @Operation(summary = "嫌疑单处理")
    public Response<Object> handle(@RequestBody @Validated RoomSuspicionOrderHandleReq roomSuspicionOrderHandleReq) {
        VillageRoomSuspicionOrderDto villageRoomSuspicionOrderDto = villageRoomSuspicionOrderService.selectCacheById(roomSuspicionOrderHandleReq.getVillageRoomSuspicionOrderId());
        if (villageRoomSuspicionOrderDto == null) {
            return Response.error("嫌疑单不存在");
        }

        VillageRoomSuspicionOrderDto updateDto = new VillageRoomSuspicionOrderDto();
        updateDto.setId(villageRoomSuspicionOrderDto.getId());
        updateDto.setHandleStatus(VillageRoomSuspicionOrderConstants.HandleStatusEnum.PROCESSED.getStatus());
        updateDto.setHandleTime(new Date());
        if (StringUtils.isNotBlank(roomSuspicionOrderHandleReq.getHandleRemark())) {
            updateDto.setHandleRemark(roomSuspicionOrderHandleReq.getHandleRemark());
        }
        updateDto.setHandleResult(roomSuspicionOrderHandleReq.getHandleResult());
        villageRoomSuspicionOrderService.updateById(updateDto);

        // 这里就算失败也没关系，可以手动标记，所以不开启事务了
        if (VillageRoomSuspicionOrderConstants.HandleResultEnum.CONFIRM.getStatus().equals(roomSuspicionOrderHandleReq.getHandleResult())) {
            // 确认为群租
            VillageRoomDto villageRoomDto = villageRoomService.selectCacheById(villageRoomSuspicionOrderDto.getRoomId());
            assert villageRoomDto != null;

            HashMap<String, Object> parse = StringUtils.isBlank(villageRoomDto.getTags())
                    ? new HashMap<>() : JacksonUtils.parse(villageRoomDto.getTags(), new TypeReference<HashMap<String, Object>>() {
            });
            parse.put(GroupRentingRoomConstants.TagsEnum.GROUP_RENTING_ROOM.getType().toString(), SystemConstants.ENABLE);

            VillageRoomDto updateRoom = new VillageRoomDto();
            updateRoom.setId(villageRoomDto.getId());
            updateRoom.setTags(JacksonUtils.toJsonString(parse));
            villageRoomService.updateById(updateRoom);
        }
        return Response.ok();
    }



    /**
     * 导出群租嫌疑单信息为excel
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "villageRoomSuspicionOrder:export")
    @Log(express = "导出群租嫌疑单信息")
    @Operation(summary = "导出群租嫌疑单信息为excel")
    public void exportExcel(@RequestParam Map<String, Object> params, HttpServletResponse hresp) {
        Request request = Request.configParamsNotPage(params);

        super.fillAuthorityData(params);

        List<VillageRoomSuspicionOrderDto> result = new ArrayList<>();
        int pageNo = 0;
        params.put("limit", 1000);
        while (true) {
            params.put("offset", pageNo++ * 1000);
            List<VillageRoomSuspicionOrderDto> list = villageRoomSuspicionOrderService.queryList(params);
            if (org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
                break;
            }
            result.addAll(list);
            if (list.size() < 1000) {
                break;
            }
        }
        String[] headers = new String[]{"所属小区", "所属楼栋", "所属楼层", "房屋名称", "房屋户型", "房屋面积", "居住人数", "业主姓名", "业主电话", "状态", "处理结果", "创建时间", "处理时间"};
        List<String[]> dataList = new ArrayList<>();
        for (VillageRoomSuspicionOrderDto data : result) {
            String[] item = new String[headers.length];
            item[0] = data.getVillageRoom() != null ? data.getVillageRoom().getVillageName() : "";
            item[1] = data.getVillageRoom() != null ? data.getVillageRoom().getBuildingName() : "";
            item[2] = data.getVillageRoom() != null ? data.getVillageRoom().getFloorName() : "";
            item[3] = data.getVillageRoom() != null ? data.getVillageRoom().getName() : "";
            item[4] = data.getVillageRoom() != null ? SysCodeUtils.easyToGetName(SysCodeKeyConstants.ROOM_TYPE, data.getVillageRoom().getRoomType() + "") : "";
            item[5] = data.getVillageRoom() != null && data.getVillageRoom().getRoomArea() != null
                    ? data.getVillageRoom().getRoomArea().setScale(2, RoundingMode.HALF_UP).toPlainString() : "";
            item[6] = data.getPeopleCount() + "";
            item[7] = data.getVillageRoom() != null ? data.getVillageRoom().getOwnerName() : "";
            item[8] = data.getVillageRoom() != null ? data.getVillageRoom().getOwnerMobile() : "";
            item[9] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.GROUP_RENTING_ROOM_HANDLE_STATUS, data.getHandleStatus() + "");
            item[10] = data.getHandleResult() != null ? SysCodeUtils.easyToGetName(SysCodeKeyConstants.GROUP_RENTING_ROOM_HANDLE_RESULT, data.getHandleResult() + "") : "";
            item[11] = data.getCreateTime() != null ? DateUtils.format(data.getCreateTime(), DateUtils.FormatType.COMMON) : "";
            item[12] = data.getHandleTime() != null ? DateUtils.format(data.getHandleTime(), DateUtils.FormatType.COMMON) : "";
            dataList.add(item);
        }
        POIUtils.exportExcel(hresp, "群租嫌疑单", headers, dataList, "群租嫌疑单");
    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "villageRoomSuspicionOrder:list")
    @Operation(summary = "分页获取群租房嫌疑单列表 请开发者检查描述")
    public Response<Page<VillageRoomSuspicionOrderDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = villageRoomSuspicionOrderService.queryTotal(request.getParams());

        List<VillageRoomSuspicionOrderDto> list = null;
        if (total > 0) {
            list = villageRoomSuspicionOrderService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<VillageRoomSuspicionOrderDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<VillageRoomSuspicionOrderDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "villageRoomSuspicionOrder:edit")
    @Operation(summary = "在编辑时根据id查询群租房嫌疑单详情 请开发者检查描述")
    public Response<VillageRoomSuspicionOrderDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (villageRoomSuspicionOrderService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        VillageRoomSuspicionOrderDto villageRoomSuspicionOrderDto = villageRoomSuspicionOrderService.selectById(id);

        return Response.<VillageRoomSuspicionOrderDto>ok().wrap(villageRoomSuspicionOrderDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "villageRoomSuspicionOrder:info")
    @Operation(summary = "根据id查询群租房嫌疑单的详情 请开发者检查描述")
    public Response<VillageRoomSuspicionOrderDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (villageRoomSuspicionOrderService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        VillageRoomSuspicionOrderDto villageRoomSuspicionOrderDto = villageRoomSuspicionOrderService.selectById(id);

        return Response.<VillageRoomSuspicionOrderDto>ok().wrap(villageRoomSuspicionOrderDto);
    }

    /**
     * 保存
     *
     * @param villageRoomSuspicionOrderDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "villageRoomSuspicionOrder:edit")
    @Operation(summary = "新增群租房嫌疑单 请开发者检查描述")
    public Response<Object> save(@RequestBody @Validated VillageRoomSuspicionOrderDto villageRoomSuspicionOrderDto) {

        //填充基础数据
        fillSaveCommonData(villageRoomSuspicionOrderDto);

        villageRoomSuspicionOrderService.save(villageRoomSuspicionOrderDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param villageRoomSuspicionOrderDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "villageRoomSuspicionOrder:edit")
    @Operation(summary = "根据id修改群租房嫌疑单 请开发者检查描述")
    public Response<Object> update(@RequestBody  @Validated VillageRoomSuspicionOrderDto villageRoomSuspicionOrderDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(villageRoomSuspicionOrderDto.getId()));
        if (villageRoomSuspicionOrderService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(villageRoomSuspicionOrderDto);

        villageRoomSuspicionOrderService.updateById(villageRoomSuspicionOrderDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "villageRoomSuspicionOrder:delete")
    @Operation(summary = "根据多条记录id批量删除群租房嫌疑单 请开发者检查描述")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (villageRoomSuspicionOrderService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        villageRoomSuspicionOrderService.deleteBatch(ids);

        return Response.ok();
    }
}
